import { ref, watch } from "vue";
import { defineStore } from "pinia";
import { Dark, LocalStorage } from "quasar";
import type { settingsProps } from "./typing";

export const useSettingsStore = defineStore("settings-store", () => {
  /**
   * state
   */
  const settings = ref<settingsProps>({
    promptToDelete: true,
    showRunningTotal: false,
    currencySymbol: "￥",
    darkMode: false, // false | true | 'auto'
  });

  // 监视主题属性
  watch(
    () => settings.value.darkMode,
    (newValue: boolean | "auto") => {
      Dark.set(newValue);
    },
    // 立即执行
    { immediate: true },
  );

  // 监视设置
  watch(settings.value, () => saveSettings());

  /**
   * getters
   */

  /**
   * actions
   */

  // 本地存储
  const saveSettings = () => LocalStorage.set("settings", settings.value);

  // 加载存储
  const loadSettings = () => {
    const saveSettings = LocalStorage.getItem("settings");
    if (saveSettings) Object.assign(settings.value, saveSettings);
  };

  /**
   * return
   */
  return {
    // state
    settings,
    // getters
    // actions
    loadSettings,
  };
});
